package com.cap.dreamcircle.View;

import android.app.Dialog;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Base.BaseActivity;
import com.cap.dreamcircle.Model.Action.KeyboardAction;
import com.cap.dreamcircle.Model.Bean.AdCommentBean;
import com.cap.dreamcircle.Model.Bean.AdCommentEntity;
import com.cap.dreamcircle.Model.Bean.ArticalDeteial;
import com.cap.dreamcircle.Model.Bean.BaseBean;
import com.cap.dreamcircle.Model.IDreamModel;
import com.cap.dreamcircle.Model.Impl.DreamModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.CommonSubscriber;
import com.cap.dreamcircle.Utils.DisplayUtil;
import com.cap.dreamcircle.Utils.KeyboardUtils;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.cap.dreamcircle.View.Adapter.AdCommentsAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import rx.functions.Action0;

/**
 * Created by liucxu on 2017/11/7.
 */

public class ArticalWebviewActivity extends BaseActivity {

    private LinearLayout back_layout;
    private TextView title_tv;
    private WebView webview;
    private String AdId;
    private boolean isLiked = false;
    private int comment_num = 0;
    private int ad_like_num = 0;

    private View dialog_view;
    private Dialog commentDialog;
    private LinearLayout close_dialog_layout_share_hare;
    private RecyclerView list_content;
//    private RelativeLayout layout_body;

    @BindView(R.id.imv_like)
    ImageView imv_like;
    @BindView(R.id.artical_like_num)
    TextView artical_like_num;
    @BindView(R.id.imv_comment)
    ImageView imv_comment;
    @BindView(R.id.artical_comment_num)
    TextView artical_comment_num;
    @BindView(R.id.edt_comment)
    EditText edt_comment;
    @BindView(R.id.layout_body)
    RelativeLayout layout_body;

    private EditText edt_comment_dialog;
    private ImageView imv_like_dialog;
    private TextView artical_like_num_dialog;
    private ImageView imv_comment_dialog;
    private TextView artical_comment_num_dialog;

    private AdCommentsAdapter adapter;
    private List<AdCommentEntity> datas = new ArrayList<>();

    private IDreamModel model;

    private String toComment="";
    private String toUserId="";

    private boolean key_from_notification;

    @Override
    public int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        model = new DreamModelImpl();
        back_layout = $(R.id.layout_back);
        title_tv = $(R.id.tv_title);
        webview = $(R.id.webview);
        back_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(key_from_notification){
                    Intent intent=new Intent(ArticalWebviewActivity.this,MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
                App.GetInstance().finishActivity(ArticalWebviewActivity.this);
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    public void setupData() {
        WebSettings wSet = webview.getSettings();
        wSet.setJavaScriptEnabled(true);
        wSet.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        wSet.setDomStorageEnabled(true);
//        wSet.setSupportZoom(true);
//        wSet.setBuiltInZoomControls(true);
        webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
//                if (url.contains("image-preview::data:")) {
//                    String local_json_data = url.substring(20,url.length());
//                } else {
//                    view.loadUrl(url);
//                }
                view.loadUrl(url);
                return true;
            }
        });
        AdId = getIntent().getStringExtra("AdId");
        key_from_notification=getIntent().getBooleanExtra("key_from_notification",false);
        queryArticalDetail();
        hasReadArtical();
        edt_comment.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    postAdComment(edt_comment.getText().toString(), false);
                }
                return false;
            }
        });
    }

    private void queryArticalDetail() {
        model.QuertyArticalDetail(AdId).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<ArticalDeteial>() {
            @Override
            public void onSuccess(ArticalDeteial response) {
                hideProgress();
                String title = response.getTitle();
                String body_content = response.getContent();
                title_tv.setText(title);
                webview.loadDataWithBaseURL(null, body_content, "text/html", "utf-8", null);
                isLiked = response.hasLiked();
                comment_num = response.getCommentCount();
                if (isLiked) {
                    imv_like.setImageResource(R.mipmap.artical_liked);
                    imv_like.setEnabled(false);
                } else {
                    imv_like.setImageResource(R.mipmap.artical_like);
                    imv_like.setEnabled(true);
                }
                ad_like_num = response.getLikeCount();
                artical_comment_num.setText(comment_num + "");
                artical_like_num.setText(ad_like_num + "");
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(ArticalWebviewActivity.this, response.getDesc());
            }
        });
    }

    private void hasReadArtical() {
        model.HasReadArtical(AdId).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {

            }

            @Override
            public void onFailure(BaseBean response) {

            }
        });
    }

    private void initDialogViews() {
        dialog_view = View.inflate(this, R.layout.dialog_artical_comments, null);
        layout_body = (RelativeLayout) dialog_view.findViewById(R.id.layout_body);
        close_dialog_layout_share_hare = (LinearLayout) dialog_view.findViewById(R.id.close_dialog_layout_share_share);
        list_content = (RecyclerView) dialog_view.findViewById(R.id.list_content);
        close_dialog_layout_share_hare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentDialog.dismiss();
                toComment = "";
                toUserId = "";
            }
        });
        edt_comment_dialog = (EditText) dialog_view.findViewById(R.id.edt_comment_dialog);
        imv_like_dialog = (ImageView) dialog_view.findViewById(R.id.imv_like_dialog);
        artical_like_num_dialog = (TextView) dialog_view.findViewById(R.id.artical_like_num_dialog);
        artical_comment_num_dialog = (TextView) dialog_view.findViewById(R.id.artical_comment_num_dialog);
        list_content.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AdCommentsAdapter(this, datas);
        list_content.setAdapter(adapter);
        edt_comment_dialog.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    postAdComment(edt_comment_dialog.getText().toString(), true);
                }
                return false;
            }
        });
        edt_comment_dialog.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
//                    toComment="";
//                    toUserId="";
                }
            }
        });
    }

    public void onEvent(KeyboardAction action) {
        toComment = action.toComment;
        toUserId = action.toUserId;
        updateEditTextBodyVisible(View.VISIBLE);
    }


    public void updateEditTextBodyVisible(int visibility) {
        edt_comment_dialog.setText("");
        if (View.VISIBLE == visibility) {
//            edt_comment_dialog.requestFocus();
            //弹出键盘
            KeyboardUtils.showSoftInput(edt_comment_dialog.getContext(), edt_comment_dialog);
        } else if (View.GONE == visibility) {
            //隐藏键盘
            KeyboardUtils.hideSoftInput(edt_comment_dialog.getContext(), edt_comment_dialog);
        }
    }

    private void initDialog() {
        commentDialog = new Dialog(this, R.style.Theme_Light_Dialog);
        //获得dialog的window窗口
        Window window = commentDialog.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        WindowManager manager = getWindowManager();
        Display display = manager.getDefaultDisplay();
        lp.height = display.getHeight() - DisplayUtil.dip2px(this, 50);
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        commentDialog.setCancelable(false);
        commentDialog.setContentView(dialog_view);
    }

    @OnClick({R.id.imv_comment, R.id.imv_like})
    void doClicks(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.imv_comment:
                queryAdComments(true);
                break;
            case R.id.imv_like:
                likeArtical();
                break;
        }
    }

    private void queryAdComments(final boolean showDialog) {
        model.QueryAdComments(AdId).subscribe(new CommonSubscriber<AdCommentBean>() {
            @Override
            public void onSuccess(AdCommentBean response) {
                if (showDialog) {
                    if (dialog_view == null) {
                        initDialogViews();
                        initDialog();
                    }
                    if (isLiked) {
                        imv_like_dialog.setImageResource(R.mipmap.artical_liked);
                        imv_like_dialog.setEnabled(false);
                    } else {
                        imv_like_dialog.setImageResource(R.mipmap.artical_like);
                        imv_like_dialog.setEnabled(true);
                        imv_like_dialog.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                likeArtical();
                            }
                        });
                    }
                    artical_comment_num_dialog.setText(comment_num + "");
                    artical_like_num_dialog.setText(ad_like_num + "");
                    edt_comment_dialog.setText(edt_comment.getText().toString());
                    adapter.setDatas(response.getCommentArray());
                    commentDialog.show();
                } else {
                    adapter.setDatas(response.getCommentArray());
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.showShortToast(ArticalWebviewActivity.this, response.getDesc());
            }
        });
    }

    private void likeArtical() {
        model.LikeArtical(AdId).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                isLiked = true;
                imv_like.setImageResource(R.mipmap.artical_liked);
                imv_like.setEnabled(false);
                ad_like_num = ad_like_num + 1;
                artical_like_num.setText(ad_like_num + "");
                if (commentDialog != null && imv_like_dialog.isShown()) {
                    commentDialog.dismiss();
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.showShortToast(ArticalWebviewActivity.this, response.getDesc());
            }
        });
    }

    private void postAdComment(String content, final boolean isDialog) {
        if (TextUtils.isEmpty(content)) {
            ToastUtils.showShortToast(ArticalWebviewActivity.this, "请输入回复内容");
        }
        model.PostAdComment(AdId, content, toComment, toUserId).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                edt_comment.setText("");
                comment_num = comment_num + 1;
                artical_comment_num.setText(comment_num + "");
                if (dialog_view != null) {
                    artical_comment_num_dialog.setText(comment_num + "");
                    edt_comment_dialog.setText("");
                }
                if (isDialog) {
                    queryAdComments(false);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.showShortToast(ArticalWebviewActivity.this, response.getDesc());
            }
        });
    }
}
